Skip to content

Exercises

Art Store

In the sandbox below, we're building an e-commerce store for an artist.

The header has a cute shopping cart button, and the button has a badge that increments as the user starts adding items to their cart:

The components are structured in the following hierarchy:

  • App
  • Header
  • CartButton

Using what we learned in the previous lesson, restructure things so that App owns the CartButton component, without changing the DOM structure at all.

Acceptance Criteria:

  • The <CartButton> element should be owned by the App component, rather than <Header>.
  • The DOM structure should not be affected (the cart button should still be a child of the <header> DOM node).
  • Bonus: Using what we learned in the “Leveraging Keys” lesson, update the code so that the “fade” animation retriggers whenever the number changes:

Code Playground

import React from 'react';

import Shop from './Shop';
import Header from './Header';

function App() {
const [cartItems, setCartItems] = React.useState([]);
function addToCart(item) {
setCartItems([...cartItems, item]);
}
return (
<>
<Header numOfItemsInCart={cartItems.length} />
<Shop paintings={DATA} addToCart={addToCart} />
</>
);
}

const DATA = [
{
id: 'summer-jubilee',
title: 'Summer Jubilee',
caption: 'Oil on canvas, 80" × 64"',
src: '/img/painting-01.jpg',
price: 12000,
},
{
id: 'spectacular-end',
title: 'A Spectacular End',
caption: 'Oil on canvas, 40" × 32"',
src: '/img/painting-02.jpg',
price: 4000,
},
{
id: 'crossing-the-chasm',
title: 'Crossing The Chasm',
caption: 'Oil on canvas, 32" × 24"',
src: '/img/painting-03.jpg',
price: 3600,
},
{
id: 'underneath',
title: 'Underneath',
caption: 'Oil on canvas, 40" × 32"',
src: '/img/painting-04.jpg',
price: 3000,
},
{
id: 'it-is-what-it-is',
title: 'It Is What It Is',
caption: 'Oil on canvas, 40" × 32"',
src: '/img/painting-05.jpg',
price: 6000,
},
]

export default App;

Solution:

Note: In this video, I share my solution, but I also talk about whether this solution is actually a good idea or not. Even if you solved the exercise without issue, I'd suggest checking out the second half of this video.

More info

This “lifting content up” concept has been covered extensively online, largely as a way to potentially improve performance. If you'd like to go deeper, I recommend the following resources:

Please consider these as optional resources, if you want to go deeper into this stuff. It's absolutely not required!